const Device = require('device');
const EventEmitter = require('events');

class DeviceManager extends EventEmitter {
  constructor() {
    super();
    this.devMap = new Map();
    this.controllerMap = new Map();
    this.init();
  }

  init() {
    // 获取当前所有已加入网络的在线设备！
    Device.list(true, (error, list) => {
      if (error) {
        console.error('Device.list error!' + error);
      } else {
        list.forEach((item) => {
          Device.info(item.devid, (error, info) => {
            if (error) {
              console.error('Device.info error!' + error);
            } else {
              this.devMap.set(item.devid, {
                devid: item.devid,
                alias: info.alias,
                report: info.report
              });
            }
          });
        });
      }
    });
    Device.on('join', async (devid, info) => {
      const dev = { devid, ...info };
      console.info('[join]:', JSON.stringify(dev));
      this.devMap.set(devid, dev);
      this.emit('join', dev);
    });
    Device.on('lost', (devid) => {
      const dev = this.devMap.get(devid);
      console.warn('[lost]:', devid, dev);
      this.devMap.delete(devid);
      if (this.controllerMap.has(devid)) {
        this.controllerMap.delete(devid);
      }
      if (!dev) {
        this.emit('error', '应用出现未知错误，请退出重试！');
      } else {
        this.emit('lost', dev);
      }
    });
  }

  // 构建设备控制对象
  generateController(devid) {
    if (this.controllerMap.has(devid)) {
      return Promise.resolve(this.controllerMap.get(devid))
    }
    const controller = new Device();
    return new Promise((resolve, reject) => {
      controller.request(devid, (error) => {
        if (error) {
          reject(error);
        } else {
          this.controllerMap.set(devid, controller);
          resolve(controller);
        }
      });
    })
  }

  // 删除控制器
  deleteController(devid) {
    this.controllerMap.delete(devid);
  }

  sendDeviceInfo(devid, data) {
    const controller = this.controllerMap.get(devid);
    if (!controller) {
      return Promise.reject('程序出现未知错误，请退出重试！')
    }
    return new Promise((resolve, reject) => {
      // console.error('[send]: ', JSON.stringify(data, '', 2))
      controller.send(data, (err) => {
        if (err) {
          // console.error('[send message error]:', err, Object.keys(err));
          reject('控制设备失败，请重试！')
        } else {
          resolve();
        }
      }, 3)
    })
  }
}

const devManager = new DeviceManager();

module.exports = {
  devManager
}



